/**
 * Global error handler middleware
 */
const errorHandler = (err, req, res, next) => {
  console.error(err.stack);

  // Default error
  let error = {
    status: err.status || 500,
    message: err.message || 'Internal Server Error',
  };

  // Validation error
  if (err.isJoi) {
    error = {
      status: 400,
      message: 'Validation Error',
      details: err.details.map(detail => ({
        field: detail.context.key,
        message: detail.message,
      })),
    };
  }

  // Database error
  if (err.code === 'ER_DUP_ENTRY') {
    error = {
      status: 409,
      message: 'Duplicate entry error',
    };
  }

  // JWT error
  if (err.name === 'JsonWebTokenError') {
    error = {
      status: 401,
      message: 'Invalid token',
    };
  }

  if (err.name === 'TokenExpiredError') {
    error = {
      status: 401,
      message: 'Token expired',
    };
  }

  res.status(error.status).json({
    error: {
      status: error.status,
      message: error.message,
      ...(error.details && { details: error.details }),
      ...(process.env.NODE_ENV === 'development' && { stack: err.stack }),
    },
  });
};

module.exports = errorHandler;